package com.wechart.controller;


import com.wechart.common.Const;
import com.wechart.dao.domain.Areainfo;
import com.wechart.dao.domain.Bankinfo;
import com.wechart.dao.domain.Prtryinfo;
import com.wechart.dao.domain.Systeminfo;
import com.wechart.model.BankInfoModel;
import com.wechart.model.SystemModel;
import com.wechart.service.system.AreainfoService;
import com.wechart.service.system.BankinfoService;
import com.wechart.service.system.PrtryinfoService;
import com.wechart.service.system.SysteminfoService;
import com.wechart.utils.*;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.*;

/**
 * Created by silenceholic on 2017/5/2.
 */
@Controller
@RequestMapping("system/")
public class SysController extends BaseController{


    @Resource(name = "bankinfoService")
    private BankinfoService bankinfoService;

    @Resource(name = "prtryinfoService")
    private PrtryinfoService prtryinfoService;

    @Resource(name = "areainfoService")
    private AreainfoService areainfoService;

    @Resource(name = "systeminfoService")
    private SysteminfoService systeminfoService;


    /**
     * 银行机构信息表查询
     * @param systemModel
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "bankinfo.htm" )
    public ModelAndView getbankinfo(@ModelAttribute SystemModel systemModel, HttpSession session){
        Map<String, Object> map = new HashMap<String, Object>();
        String areacode = ((Auth)session.getAttribute(Const.SESSION_USER)).getUser().getAreacode();
        systemModel.setAreacode(areacode);
        List<Bankinfo> data = bankinfoService.getBankinfo(systemModel);
        map.put("data",data);
        map.put("recordsTotal", data.size());
        map.put("recordsFiltered", data.size());
        map.put("banklevels", CommonOption.getBanklevelOption());
        map.put("bankstats",CommonOption.getBankstatOption());
        map.put("bankcode", systemModel.getBankcode());
        map.put("bankname", systemModel.getBankname());
        map.put("bankstat", systemModel.getBankstat());
        ModelAndView mv = super.modelAndView(map);
        mv.setViewName("system/bankinfo");
        return mv;

    }

    /**
     * 插入银行机构信息表
     * @param bankInfoModel
     * @return
     */
    @RequestMapping(value = "insert/bankinfo.do" ,method = RequestMethod.POST)
    public Object insertBankinfo(@ModelAttribute BankInfoModel bankInfoModel, HttpSession session){
        String areacode = ((Auth)session.getAttribute(Const.SESSION_USER)).getUser().getAreacode();
        bankInfoModel.setAreacode(areacode);
        if (bankinfoService.insertBankinfo(bankInfoModel)==1) {
            return "redirect:" + Const.CONTROLLER_SYSTEM_BANKINFO;
        }else{
            return "redirect:" + Const.CONTROLLER_SYSTEM_BANKINFO;//先这样写，错误页面需要再做到时候跳转错误提示
        }

    }


    /**
     * 修改银行机构信息表跳转
     * @param id
     * @return
     **/
    @RequestMapping(value = "modify/bankinfo.htm" )
    public ModelAndView modifyBankinfoDispatch(@RequestParam(value = "id", required = false) String id){
        Map<String, Object> map = new HashMap<String, Object>();
        Bankinfo data = bankinfoService.getBankinfoById(Integer.parseInt(id));
        map.put("item",data);
        ModelAndView mv = super.modelAndView(map);
        mv.setViewName("system/modifybankinfo");
        return mv;
//        return "system/modifybankinfo";

    }

    /**
     * 修改银行机构信息表
     * @param bankInfoModel
     * @return
     */
    @RequestMapping(value = "modify/bankinfo.do" ,method = RequestMethod.POST)
    public Object modifyBankinfo(@ModelAttribute BankInfoModel bankInfoModel,
                                 @RequestParam(value = "id", required = false) String id){
        bankinfoService.modifyBankinfo(bankInfoModel,Integer.parseInt(id));
        return "redirect:" + Const.CONTROLLER_SYSTEM_BANKINFO;

    }

    /**
     * 业务种类信息表查询
     * @param systemModel
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "prtryinfo.htm" )
    public ModelAndView getprtryinfo(@ModelAttribute SystemModel systemModel){
        Map<String, Object> map = new HashMap<String, Object>();
        List<Prtryinfo> data = prtryinfoService.getPrtryinfo(systemModel);
        map.put("data",data);
        map.put("recordsTotal", data.size());
        map.put("recordsFiltered", data.size());
        map.put("code", systemModel.getCode());
        ModelAndView mv = super.modelAndView(map);
        mv.setViewName("system/prtryinfo");
        return mv;

    }


    /**
     * 地区信息表查询
     * @param systemModel
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "areainfo.htm" )
    public ModelAndView getAreainfo(@ModelAttribute SystemModel systemModel){
        Map<String, Object> map = new HashMap<String, Object>();
        List<Areainfo> data = areainfoService.getAreainfo(systemModel);
        map.put("data",data);
        map.put("recordsTotal", data.size());
        map.put("recordsFiltered", data.size());
        map.put("code", systemModel.getCode());
        ModelAndView mv = super.modelAndView(map);
        mv.setViewName("system/areainfo");
        return mv;

    }

//    /**
//     *系统信息跳转
//     * @return
//     */
//    @RequestMapping(value = "systeminfo.htm")
//    public String allSysteminfo(){
//        return "system/systeminfo";
//    }

    /**
     * 系统信息查询
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "systeminfo.htm" )
    public ModelAndView getSysteminfo(@ModelAttribute SystemModel systemModel){
        Map<String, Object> map = new HashMap<String, Object>();
        List<Systeminfo> data = systeminfoService.getSysteminfo(systemModel);
        map.put("data",data);
        map.put("recordsTotal", data.size());
        map.put("recordsFiltered", data.size());
        map.put("start", systemModel.getStart());
        map.put("end", systemModel.getEnd());
        map.put("code", systemModel.getCode());
        ModelAndView mv = super.modelAndView(map);
        mv.setViewName("system/systeminfo");
        return mv;

    }

    /**
     * 插入地区信息表
     * @param systemModel
     * @return
     */
    @RequestMapping(value = "insert/areainfo.do" ,method = RequestMethod.POST)
    public Object insertAreainfo(@ModelAttribute SystemModel systemModel){

        if (areainfoService.insertAreainfo(systemModel)==1) {
            return "redirect:" + Const.CONTROLLER_SYSTEM_AREAINFO;
        }else{
            return "redirect:" + Const.CONTROLLER_SYSTEM_AREAINFO;//先这样写，错误页面需要再做到时候跳转错误提示
        }
    }
    /**
     * 修改地区信息表跳转
     * @param
     * @return
     **/
    @RequestMapping(value = "modify/areainfo.htm" )
    public ModelAndView modifyAreainfoDispatch(@RequestParam(value = "id", required = false) String id){
        Map<String, Object> map = new HashMap<String, Object>();
        Areainfo data = areainfoService.getAreainfoById(Integer.parseInt(id));
        map.put("item",data);
        ModelAndView mv = super.modelAndView(map);
        mv.setViewName("system/modifyareainfo");
        return mv;
    }

    /**
     * 修改地区信息表
     * @param
     * @return
     */
    @RequestMapping(value = "modify/areainfo.do" ,method = RequestMethod.POST)
    public Object modifyBankinfo(@ModelAttribute SystemModel systemModel,
                                 @RequestParam(value = "id", required = false) String id){
        areainfoService.modifyAreainfo(systemModel,Integer.parseInt(id));
        return "redirect:" + Const.CONTROLLER_SYSTEM_BANKINFO;

    }
    /**
     * 插入业务类型信息表
     * @param systemModel
     * @return
     */
    @RequestMapping(value = "insert/prtryinfo.do" ,method = RequestMethod.POST)
    public Object insertPrtryinfo(@ModelAttribute SystemModel systemModel){

        if (prtryinfoService.insertPrtryinfo(systemModel)==1) {
            return "redirect:" + Const.CONTROLLER_SYSTEM_PRTRYINFO;
        }else{
            return "redirect:" + Const.CONTROLLER_SYSTEM_PRTRYINFO;//先这样写，错误页面需要再做到时候跳转错误提示
        }
    }
    /**
     * 跳转到修改业务种类信息表
     * @param
     * @return
     **/
    @RequestMapping(value = "modify/prtryinfo.htm" )
    public ModelAndView modifyPrtryinfoDispatch(@RequestParam(value = "id", required = false) String id){
        Map<String, Object> map = new HashMap<String, Object>();
        Prtryinfo data = prtryinfoService.getPrtryinfoById(Integer.parseInt(id));
        map.put("item",data);
        ModelAndView mv = super.modelAndView(map);
        mv.setViewName("system/modifyprtryinfo");
        return mv;
    }

    /**
     * 修改业务信息表
     * @param
     * @return
     */
    @RequestMapping(value = "modify/prtryinfo.do" ,method = RequestMethod.POST)
    public Object modifyPrtryinfo(@ModelAttribute SystemModel systemModel,
                                 @RequestParam(value = "id", required = false) String id){
        prtryinfoService.modifyPrtryinfo(systemModel,Integer.parseInt(id));
        return "redirect:" + Const.CONTROLLER_SYSTEM_PRTRYINFO;

    }
    /**
     * 插入系统信息表
     * @param systemModel
     * @return
     */
    @RequestMapping(value = "insert/systeminfo.do" ,method = RequestMethod.POST)
    public Object insertSysteminfo(@ModelAttribute SystemModel systemModel){

        if (systeminfoService.insertSysteminfo(systemModel)==1) {
            return "redirect:" + Const.CONTROLLER_SYSTEM_SYSTEMINFO;
        }else{
            return "redirect:" + Const.CONTROLLER_SYSTEM_SYSTEMINFO;//先这样写，错误页面需要再做到时候跳转错误提示
        }
    }
    /**
     * 跳转到修改系统信息表
     * @param
     * @return
     **/
    @RequestMapping(value = "modify/systeminfo.htm" )
    public ModelAndView modifySysteminfoDispatch(@RequestParam(value = "id", required = false) String orgcode){
        Map<String, Object> map = new HashMap<String, Object>();
        Systeminfo data = systeminfoService.getSysteminfoById(orgcode);
        map.put("item",data);
        ModelAndView mv = super.modelAndView(map);
        mv.setViewName("system/modifysysteminfo");
        return mv;
    }

    /**
     * 修改系统信息表
     * @param
     * @return
     */
    @RequestMapping(value = "modify/systeminfo.do" ,method = RequestMethod.POST)
    public Object modifySysteminfo(@ModelAttribute SystemModel systemModel){
        systeminfoService.modifySysteminfo(systemModel);
        return "redirect:" + Const.CONTROLLER_SYSTEM_SYSTEMINFO;

    }
    /**
     * 取得银行名称
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "select/getBankname.do")
    public Object selectBankname(@RequestParam(value = "q",required = false) String  name){
        return bankinfoService.selectBankname(name);
    }

    /**
     * 业务种类下载
     * @param systemModel
     * @return
     */
    @RequestMapping(value = "downloadPrtryinfo.do" , method = { RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<byte[]> downloadPrtryinfoTables(@ModelAttribute SystemModel systemModel, HttpSession session)
            throws Exception{
        List<Prtryinfo> data = prtryinfoService.getPrtryinfo(systemModel);
        HttpHeaders headers = new HttpHeaders();
        String file = DateUtil.formate(new Date(), "FULL");
        String fileName = new String((file + ".csv").getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(CsvWriter.print(data), headers, HttpStatus.CREATED);

    }
    /**
     * 银行信息下载
     * @param systemModel
     * @return
     */
    @RequestMapping(value = "downloadBankinfo.do" , method = { RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<byte[]> downloadBankinfoTables(@ModelAttribute SystemModel systemModel, HttpSession session)
            throws Exception{
        List<Bankinfo> data = bankinfoService.getBankinfo(systemModel);
        HttpHeaders headers = new HttpHeaders();
        String file = DateUtil.formate(new Date(), "FULL");
        String fileName = new String((file + ".csv").getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(CsvWriter.print(data), headers, HttpStatus.CREATED);

    }
    /**
     * 地区信息下载
     * @param systemModel
     * @return
     */
    @RequestMapping(value = "downloadAreainfo.do" , method = { RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<byte[]> downloadAreainfoTables(@ModelAttribute SystemModel systemModel, HttpSession session)
            throws Exception{
        List<Areainfo> data = areainfoService.getAreainfo(systemModel);
        HttpHeaders headers = new HttpHeaders();
        String file = DateUtil.formate(new Date(), "FULL");
        String fileName = new String((file + ".csv").getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(CsvWriter.print(data), headers, HttpStatus.CREATED);

    }
    /**
     * 系统信息下载
     * @param systemModel
     * @return
     */
    @RequestMapping(value = "downloadSysteminfo.do" , method = { RequestMethod.GET, RequestMethod.POST})
    public ResponseEntity<byte[]> downloadSysteminfoTables(@ModelAttribute SystemModel systemModel, HttpSession session)
            throws Exception{
        List<Systeminfo> data = systeminfoService.getSysteminfo(systemModel);
        HttpHeaders headers = new HttpHeaders();
        String file = DateUtil.formate(new Date(), "FULL");
        String fileName = new String((file + ".csv").getBytes("UTF-8"), "iso-8859-1");//为了解决中文名称乱码问题
        headers.setContentDispositionFormData("attachment", fileName);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(CsvWriter.print(data), headers, HttpStatus.CREATED);

    }

    /**
     * 取得地区编号和名称
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "select/areaIdAndName.do")
    public Object selectAreaidAndName(@RequestParam(value = "q",required = false) String  name){
        return areainfoService.selectAreaidAndName(name);
    }

//    /**
//     * 跳转到批量导入页面
//     * @return
//     */
//    @RequestMapping(value = "batchBankImport.htm")
//    public String batchBankImportForward(){
//        return "system/batchBankImport";
//    }

    /**
     * 处理批量导入文件
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "batchBankImport.do")
    public ModelAndView batchBankImport(@RequestParam(value = "file", required = false) MultipartFile file, HttpServletRequest request){
        String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
        String fieldsTmp[] = null; // 保存记录中的各个字段
        List<String> result=new ArrayList<String>();
        // 总记录数、成功记录数、失败记录数
        int count = 0, succCount = 0, failCount = 0;
        System.out.println(path);
        File targetFile = new File(path, fileName);
        if(!targetFile.exists()){
            //查看目录是否存在，如何不存在就创建这个目录
            targetFile.mkdirs();
        }
        result.add("操作失败结果明细信息显示如下(后面显示统计结果):");
        result.add("********************************************");
        InputStream in = null;
        try {
            file.transferTo(targetFile);
            in = new FileInputStream(targetFile);//通过对象多态性，进行实例化
            Import imp = ImportFactory.getImporter("xls", in);
            imp.readLine();
            while ((fieldsTmp = imp.readLine()) != null) {
                ++count;
                if (fieldsTmp.length > 0) {
                    if ((fieldsTmp == null) || (fieldsTmp.length != 15)) {
                        result.add("第" + count + "行==>记录字段数目不对,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[0].toString().trim().equals("") || fieldsTmp[0].trim().length() > 14) {
                        result.add("第" + count + "行==>银行代码为空或者大于14位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[1].toString().trim().equals("") || fieldsTmp[1].trim().length() > 128) {
                        result.add("第" + count + "行==>银行名称为空或者大于128位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[2].trim().length() > 1) {
                        result.add("第" + count + "行==>银行类型大于1位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[3].trim().length() > 1) {
                        result.add("第" + count + "行==>银行级别大于1位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[4].trim().length() > 14) {
                        result.add("第" + count + "行==>上级银行机构代码大于14位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[5].trim().length() > 14) {
                        result.add("第" + count + "行==>所属清算行大于14位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[6].trim().length() > 6) {
                        result.add("第" + count + "行==>行政区域大于6位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[7].trim().length() > 4) {
                        result.add("第" + count + "行==>地区代码大于4位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[8].trim().length() > 32) {
                        result.add("第" + count + "行==>业务类型列表大于32位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[9].trim().length() > 60) {
                        result.add("第" + count + "行==>联系人大于60位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[10].trim().length() > 20) {
                        result.add("第" + count + "行==>联系电话大于20位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[11].trim().length() > 4 || !StringUtils.isInteger(fieldsTmp[11])) {
                        result.add("第" + count + "行==>银行状态大于4位或者不为整数,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[12].trim().length() > 8 ) {
                        result.add("第" + count + "行==>启用日期大于8位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[13].trim().length() > 8 ) {
                        result.add("第" + count + "行==>停用日期大于8位,请检查");
                        ++failCount;
                        continue;
                    }
                    else if (fieldsTmp[14].trim().length() > 8 ) {
                        result.add("第" + count + "行==>最后修改日期大于8位,请检查");
                        ++failCount;
                        continue;
                    }else{
                        bankinfoService.insertBankinfoByArray(fieldsTmp);
                        ++succCount;
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            System.out.println("转换文件失败，或文件未找到！"+e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
        result.add("---------------------统计结果如下-----------------------");
        result.add("文本总行数:" + count );
        result.add("成功记录数："+succCount);
        result.add("失败记录数："+failCount);
        result.add("空行数："+(count-succCount-failCount));
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("data",result);
        ModelAndView mv = super.modelAndView(map);
        mv.setViewName("system/batchBankImport");
        return mv;
    }



}
